package com.xiaoyu.fish.service.impl;

import com.xiaoyu.fish.common.Result;
import com.xiaoyu.fish.dto.LocationDto;
import com.xiaoyu.fish.mapper.PositioningMapper;
import com.xiaoyu.fish.pojo.Callout;
import com.xiaoyu.fish.pojo.Location;
import com.xiaoyu.fish.pojo.Position;
import com.xiaoyu.fish.service.PositioningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PositioningServiceImpl implements PositioningService {

    @Autowired
    private PositioningMapper positioningMapper;
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
    private Map<String, Integer> indexMap = new HashMap<>();


    @Override
    public List<Position> listPosition() {
        List<Position> positionList = positioningMapper.selectALLPoint();
        System.out.println(positionList);
        return positionList;
    }

    @Override
    public String savePoint(Position position) {
//        创建时间
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("MM月dd日");
        LocalDate localDate = LocalDate.now();
        String formatTime = pattern.format(localDate);
        System.out.println("============>" + formatTime);
        position.setCreate_time(formatTime);
//        网的序号
        Integer integer = indexMap.get(position.getCreate_time());
        if (integer == null) {
//            不存在则给这个时间默认1
            indexMap.put(position.getCreate_time(), 1);
        } else {
//            存在则取出加1
            Integer index = indexMap.get(position.getCreate_time());
            indexMap.put(position.getCreate_time(), index + 1);
        }
        Integer integer1 = indexMap.get(position.getCreate_time());
        position.setIndex_net(integer1);
        positioningMapper.savePoint(position);
        return "保存成功！";
    }

    @Override
    @Cacheable(value = "position", key = "#id")
    public Position selectOne(int id) {
        System.out.println("看看我执行了吗");
//        System.out.println(jdbcTemplate);
        Position position = positioningMapper.selectOne(id);
        return position;
    }

    @Override
    public String deleteById(int id) {

        //根据id查出position
        Position position = positioningMapper.selectOne(id);
        Integer integer = indexMap.get(position.getCreate_time());

        if (integer > 1) {
            indexMap.put(position.getCreate_time(), integer - 1);
        } else {
            //如果是第一排要删除则删除整个key
            indexMap.remove(position.getCreate_time());
        }
        System.out.println("=======================");
        System.out.println(indexMap.get(position.getCreate_time()));
        positioningMapper.deleteById(id);
        return "删除成功！";
    }


}
